package server

import (
	"chatServer/src/jsonEntity"
	"chatServer/src/msgConst"
	"chatServer/src/util"
	"fmt"
	"net"
	"sync"
)

//Server 服务器结构
type Server struct {
	address string
	channel chan string
	// 所有用户
	userMap map[string]*User
	// 用户列表锁
	userMapLock sync.RWMutex
	// 所有房间
	roomMap map[int]*ChatRoom
}

//ChatServer 服务器单列
var ChatServer *Server

// CreateServer 创建服务器
func CreateServer(cfg jsonEntity.ServerConf) {
	address := fmt.Sprintf("%s:%d", cfg.Ip, cfg.Port)
	ChatServer = &Server{
		address: address,
		channel: make(chan string),
		userMap: make(map[string]*User),
		roomMap: make(map[int]*ChatRoom)}
	for _, roomCfg := range cfg.RoomList {
		ChatServer.roomMap[roomCfg.RoomID] = createChatRoom(roomCfg)
	}
}

//Start 服务器启动
func (s *Server) Start() {
	listener, err := net.Listen("tcp", s.address)
	util.HandleErr(err)
	fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>服务器启动成功,当前IP地址是: ", s.address)
	fmt.Println("GM命令1:", msgConst.GmStats+"#用户名 查询用户状态")
	fmt.Println("GM命令2:", msgConst.GmPopular+"#房间号 查询房间热度消息")
	for {
		conn, err := listener.Accept()
		if err != nil {
			util.HandleErr(err)
			continue
		}
		go s.connHandle(conn)
	}
}

// 连接处理
func (s *Server) connHandle(conn net.Conn) {
	createUser(conn)
}

// 添加用户
func (s *Server) addUser(u *User) {
	s.userMapLock.Lock()
	defer s.userMapLock.Unlock()
	s.userMap[u.userName] = u
}

// 用户名修改
func (s *Server) userRename(oldName string, u *User) {
	s.userMapLock.Lock()
	defer s.userMapLock.Unlock()
	delete(s.userMap, oldName)
	s.userMap[u.userName] = u
}

//GetUserMap 获取用户map
func (s *Server) GetUserMap() map[string]*User {
	return s.userMap
}

//GetRoomMap 获取房间map
func (s *Server) GetRoomMap() map[int]*ChatRoom {
	return s.roomMap
}
